var request = new XMLHttpRequest();
request.open("GET", chrome.extension.getURL('manifest.json'));
request.onreadystatechange = function() {
    if (this.readyState == XMLHttpRequest.DONE) {
        $('#version').html('v '+JSON.parse(this.responseText).version);
    }
};
request.send();

var urlParams;
function getParams(key) {
	if (!urlParams) {
		var p,
		    urlParams={},
			tmp = location.search.substring(1).split('&');
		tmp.forEach(function(item, idx){
			p = item.split('=');
			urlParams[p[0]] = p[1];
		})
	}

	if (key) {
		return urlParams[key];
	}
}

var _m = chrome.i18n.getMessage,
    bg = chrome.extension.getBackgroundPage(),
	userInfo = bg.storage.get('user_info'),
	optionsHotkey = bg.storage.get('options_hotkey'),
	enableTabs = bg.storage.get('options_enableTabs'),
	enableAnalysisHelper = bg.storage.get('options_enableAnalysisHelper'),
	enableSuperAutoNextPage = bg.storage.get('options_enableSuperAutoNextPage'),
	enableShareBtn = bg.storage.get('options_enableShareBtn'),
	enableRightMenu = bg.storage.get('options_enableRightMenu'),
	skinSetting = bg.storage.get('setting_textSkin');
	hotkeyInputs = document.querySelectorAll('input[type="text"]'),
	i18nEles = document.querySelectorAll('*[i18n]');

for(var i=0;i<i18nEles.length;i++){
    var item = i18nEles[i];
	item.innerHTML = _m(item.getAttribute('i18n'));	
}

if (!optionsHotkey){
    optionsHotkey = {
        enable:false,
        image:'Ctrl+Alt+I',
        text:'Ctrl+Alt+T',
        link:'Ctrl+Alt+L'
    }
}

function setHotkeyEnable(){
    for(var i=0;i<hotkeyInputs.length;i++){
        var item =hotkeyInputs[i], key = item.id.replace('HotkeyValue', ''); 
        item.value = optionsHotkey[key];
        item.disabled = !optionsHotkey.enable;
    }
}
function showSaveResult(res){
	var text = res.msg||(res.suc ? _m('optionsSaveSuccess') : _m('optionsSaveFail'));
	$('#saveMessage').html(text).css({opacity:1});
	setTimeout(function(){
		$('#saveMessage').css({opacity:0})
	}, 2000);
}
$('#hotkeyEnable').attr({
	checked:optionsHotkey.enable, 
	onchange:function(){
		optionsHotkey.enable = this.checked;
		setHotkeyEnable();
		for(var i=0;i<hotkeyInputs.length;i++){
            var item =hotkeyInputs[i] , key = item.id.replace('HotkeyValue', ''); 
            optionsHotkey[key] = item.value.trim();
        }
		bg.storage.set('options_hotkey', optionsHotkey);
	}
});
$('#saveBtn').attr({
	onclick:function(){
		$('#saveMessage').html(_m('optionsConfigSaving')).css({opacity:1});
		bg.syncConfigToCloud(function(res){
			showSaveResult(res);
		});
	}
});
setHotkeyEnable();
(function(){
	if (enableAnalysisHelper === ''){
		enableAnalysisHelper = 1;
		bg.storage.set('options_enableAnalysisHelper', enableAnalysisHelper);
	}
	enableAnalysisHelper && $('#enableAnalysisHelper').attr({checked:true});
	$('#enableAnalysisHelper').attr({onchange:function(){
		bg.storage.set('options_enableAnalysisHelper', this.checked|0);
	}});
	
	if (enableSuperAutoNextPage === ''){
		enableSuperAutoNextPage = 1;
		bg.storage.set('options_enableSuperAutoNextPage', enableSuperAutoNextPage);
	}
	enableSuperAutoNextPage && $('#enableSuperAutoNextPage').attr({checked:true});
	$('#enableSuperAutoNextPage').attr({onchange:function(){
		bg.storage.set('options_enableSuperAutoNextPage', this.checked|0);
	}});

	for(var idx in enableTabs) {
		$('#enable'+idx+'Tab').attr({checked:enableTabs[idx]});
	}
	$('#enableLinkTab').attr({onchange:function(){
		bg.storage.set('options_enableTabs', {Img:1,Text:1,Link:this.checked|0});
	}});

    if (enableShareBtn === ''){
        enableShareBtn = 1;
        bg.storage.set('options_enableShareBtn', enableShareBtn);
    }	
	enableShareBtn && $('#enableShareBtn').attr({checked:true});
    $('#enableShareBtn').attr({onchange:function(){
        bg.storage.set('options_enableShareBtn', this.checked|0);
		bg.broadcast({action:'updateShareBtn',value:this.checked|0});
    }});
	
	if (enableRightMenu === '') {
		enableRightMenu = 1;
		bg.storage.set('options_enableRightMenu', enableRightMenu);
	}
	enableRightMenu && $('#enableRightMenu').attr({checked:true});
	$('#enableRightMenu').attr({onchange:function(){
		var checked = this.checked|0;
		bg.storage.set('options_enableRightMenu', checked);
		checked ? bg.initRightMenu() : bg.destoryRightMenu(); 
	}});
})();

(function(){
	function lie(e,b){b=b.length;for(var c=e.split(''),a=0,d;d=c[a];a++)c[a]=String.fromCharCode(d.charCodeAt()+a+b*(a%2?1:-1));return escape(c.join(''))}
	function isEmail(a){var b=a.split('@').shift(),fisrtChr=lastChr=/[a-zA-Z0-9]/,pattern=/^([a-zA-Z0-9-_.]){2,42}@([a-zA-Z0-9.]){2,}(\.(com|cn|net|org|edu|gov)){1}$/i;return(pattern.test(a)&&fisrtChr.test(b.substr(0,1))&&lastChr.test(b.substr(b.length-1,1)))?true:false}
	function showErr(msg){
        $('#notify').css({color:'red'}).html(msg);
	}
	function showWelcome(username){
        $('#notify').html('');
        $('#loginPanel').html('<p class="wel">'+_m('optionsWelcome')+'</p><b>'+username+'</b><p ></p><p class="error"><br/><a href="'+bg.listUrl+'?id='+(parseInt(userInfo.uid)+100000)+'">'+_m('collectionUrl')+'</a></p>');
	}
	function submit(type){
        var type = (type == 'login') ? 'checkuser' : 'adduser',
            emailVal = $('#email').val().trim(),
            passVal = $('#password').val().trim(), 
            url= bg.baseUrl+"?type="+type+"&username="+lie(emailVal, passVal)+"&password="+lie(passVal, emailVal);

        if (!emailVal || !isEmail(emailVal)){
            showErr(_m('optionsLoginInvalidEmail'));
            return;
        }
		if (passVal.length < 6 || passVal.length > 20) {
			showErr(_m('optionsLoginInvalidPassword'));
			return;
		}
		
		$('#saveMessage').html(_m('optionsLogging')).css({opacity:1});
        bg.ajax(url, '', 'get', function(res){
            if (res.suc == '1'){
                delete res.suc;
				delete res.errmsg;
				userInfo = res;
                bg.storage.set('user_info', res);
				bg.syncLoginInfo();
                bg.syncConfigFromCloud();
                showSaveResult({suc:1,msg:_m('optionsConfigSyncing')});
                showWelcome(res.name);
            }else{
				$('#saveMessage').css({opacity:0});
                showErr(res.errmsg || _m('optionsLoginErrorPassword'));
            }
        });
    }
	
	if (userInfo.uid && userInfo.token && userInfo.name){
		showWelcome(userInfo.name);
	}else{
	    $('#email').attr({
	        onchange:function(){
	            var val = this.value.trim();
	            if (!val || !isEmail(val)) {
	                showErr(_m('optionsLoginInvalidEmail'));
	                this.select();
	            }
	        }
	    });
	    $('#password').attr({
			onchange:function(){
		        var len = this.value.trim().length;
		        if (len < 6 || len > 20){
		            showErr(_m('optionsLoginInvalidPassword'));
		            this.select();
		        }
		    },
			onkeydown:function(e){
                e.keyCode==13 && submit('login');
		    }
		});
	    $('#login').attr({onclick:function(){
	        submit('login');
	    }});
	    $('#reg').attr({onclick:function(){
	        submit('reg');
	    }});
	}
	$('#userInfoPanel').show();

	if (getParams('src') == 'collect' || getParams('src') == 'download') {
		showErr(_m('optionsLoginMsgForCollectOrDownload'));
		$('#email')[0].focus();
	}
})();

//listen to msg for config update
chrome.extension.onConnect.addListener(function(port){
    port.onMessage.addListener(function(msg){
        if (msg.action == 'syncConfig') {
            var newConfig = JSON.parse(msg.value);
            
			optionsHotkey = newConfig.options_hotkey;
			$('#hotkeyEnable').attr({checked:optionsHotkey.enable});
			setHotkeyEnable();
			
			enableAnalysisHelper = newConfig.options_enableAnalysisHelper;
			$('#enableAnalysisHelper').attr({checked:!!enableAnalysisHelper});
			enableSuperAutoNextPage = newConfig.options_enableSuperAutoNextPage;
			$('#enableSuperAutoNextPage').attr({checked:!!enableSuperAutoNextPage});
			enableTabs = newConfig.options_enableTabs||{Img:1,Text:1,Link:0};
			for(var idx in enableTabs) {
		        $('#enable'+idx+'Tab').attr({checked:enableTabs[idx]});
		    }
			enableShareBtn = newConfig.options_enableShareBtn;
            $('#enableShareBtn').attr({checked:!!enableShareBtn});
			enableRightMenu = newConfig.options_enableRightMenu;
            $('#enableRightMenu').attr({checked:!!enableRightMenu});
			showSaveResult({suc:1,msg:_m('optionsSyncComplete')});
        }
    });
});
